package com.geese.util;

import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;

import com.geese.common.entity.Permission;
import com.geese.common.entity.Role;
import com.geese.common.util.BeanUtil;
import com.geese.module.security.dto.PermissionDto;
import com.google.common.collect.Lists;

public abstract class CommonUtil {

	public static List<Integer> getRoleIdSet(List<Role> roleList) {
		List<Integer> result = Lists.newArrayList();
		for (Role role : roleList) {
			result.add(role.getId());
		}
		return result;
	}
	
	public static List<PermissionDto> getPermissionList(List<Permission> permissionList) {
		List<Permission> tempPermissionList = permissionList;
		if (CollectionUtils.isEmpty(tempPermissionList)) {
			return Lists.newArrayList();
		}
		List<PermissionDto> result = Lists.newArrayList();
		List<Permission> topList = Lists.newArrayList();
		List<Permission> childrenList = Lists.newArrayList();
		for (Permission permission : tempPermissionList) {
			if (Objects.equals(permission.getParentId(), 1)) {
				topList.add(permission);
			} else {
				childrenList.add(permission);
			}
		}
		for (Permission top : topList) {
			PermissionDto dto = BeanUtil.map(top, PermissionDto.class);
			dto.setChildPermission(getChildPermission(top.getId(), childrenList));
			result.add(dto);
		}
		return result;
	}

	private static List<PermissionDto> getChildPermission(Integer parentId, List<Permission> permissionList) {
		List<PermissionDto> result = Lists.newArrayList();
		List<Permission> tempList = Lists.newArrayList();
		List<Permission> childList = Lists.newArrayList();
		for (Permission permission : permissionList) {
			if (Objects.equals(parentId, permission.getParentId())) {
				childList.add(permission);
			} else {
				tempList.add(permission);
			}
		}
		if (childList.size() > 0) {
			for (Permission child : childList) {
				PermissionDto dto = BeanUtil.map(child, PermissionDto.class);
				if (tempList.size() > 0) {
					dto.setChildPermission(getChildPermission(child.getId(), tempList));
				}
				result.add(dto);
			}
		}
		return result;
	}
	
}
